package database

import (
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"pool/pool_backend/config"
	"pool/pool_backend/internal/models"
	appLogger "pool/pool_backend/pkg/logger"
)

var DB *gorm.DB

// InitDB 初始化数据库连接
func InitDB(cfg *config.DatabaseConfig) error {
	var err error

	// 日志设置
	gormLogger := logger.New(
		&GormLogWriter{},
		logger.Config{
			SlowThreshold:             time.Second, // 慢查询阈值
			LogLevel:                  logger.Info, // 日志级别
			IgnoreRecordNotFoundError: true,        // 忽略记录未找到错误
			Colorful:                  false,       // 禁用彩色输出
		},
	)

	// 创建数据库连接
	DB, err = gorm.Open(mysql.Open(cfg.DSN()), &gorm.Config{
		Logger: gormLogger,
	})
	if err != nil {
		return err
	}

	// 设置连接池
	sqlDB, err := DB.DB()
	if err != nil {
		return err
	}

	sqlDB.SetMaxIdleConns(cfg.MaxIdleConns)
	sqlDB.SetMaxOpenConns(cfg.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Duration(cfg.ConnMaxLifetime) * time.Second)

	// 自动迁移模型
	err = DB.AutoMigrate(
		&models.User{},
		&models.ClaimRecord{},
		&models.CheckInRecord{},
	)
	if err != nil {
		return err
	}

	appLogger.Info("Database connected and migrated successfully")
	return nil
}

// GetDB 获取数据库连接
func GetDB() *gorm.DB {
	return DB
}

// GormLogWriter 实现gorm日志接口
type GormLogWriter struct{}

// Printf 实现gorm日志接口
func (w *GormLogWriter) Printf(format string, args ...interface{}) {
	appLogger.InfoF(format, args...)
} 